import datetime
#from lxml import etree
from django.core.cache import cache
from django.views.generic.list_detail import object_list
from django.shortcuts import render_to_response, get_object_or_404
from distutils.log import debug
import csv
from ximport.models import UploadFile
from tradinglist.models import TradinglistNorm
#from asset.models import Asset, Market, CST, MyConstants, TimeLevel
#from asset.admin import MarketAdmin
from jrcmodel.models import TimeLevel, Asset, CST, Market, MyConstants, JrcParameter, JrcSystem,\
    Portfolio, EuroConv, DvRatio, FuturesTradesAmount
#from parameter.models import JrcSystem, JrcParameter
from django.utils.version import get_svn_revision
from django.views.generic.edit import DeleteView
import django
from django.contrib import messages
from logging import CRITICAL
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from jrcconfig.models import JrcConfig
from django.template.context import RequestContext
import os
from django.utils import simplejson
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from decimal import Decimal, InvalidOperation, getcontext
from test.models import Signals
from django.test import signals
from django.views.generic.list import ListView
from django.contrib.auth.forms import UserChangeForm
from settings import TEMPLATE_DIRS
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import login_required, permission_required
import logging
import urllib2
from tracking.models import TrackRecordForex
#from test.models import Uid

class UidDetailView(DetailView):
    
    def get(self, request, **kwargs):
#        try:
#            self.object = self.get_object()
#        except Uid.DoesNotExist:
#            return HttpResponseRedirect("/help/baduid/")
#        context = self.get_context_data(object=self.object)
#        return render_to_response(context)
#    
##    def get_context_data(self, **kwargs):
##        return HttpResponseRedirect("/")
#    
#    def get_object(self):
##        return Uid()
##        print "UID: %s" % self.request.GET.get("uid")
##        print "UID: %s" % self.uid
##        return HttpResponseRedirect("/pet/rfipor1/")
#        object = Uid.get_and_validate("uid")
##        return super(DetailView, self).get_object()
        pass

class TestDeleteView(DeleteView):
    model = CST
    pass

class CstForPortfolioDetailView(DetailView):
    template_name = "test/getcstforport.html"
    model = CST

#    def get_context_data(self, **kwargs):
#        context = super(DetailView, self).get_context_data(**kwargs)
#        return context


class PortfolioDetailView(TemplateView):
    template_name = "test/portfolio_with_cst.html"
    
    def get_context_data(self, **kwargs):
        context = {}
        
        pk = 0
        
        try:
            pk = int(kwargs["pk"])
            print "PK: %s" % kwargs["pk"]
        except KeyError, ValueError:
            pk = 0
        
        if pk > 0:
            context["portfolio"] = Portfolio.objects.get(pk = pk)
        else:
            context["portfolio"] = Portfolio()
        context["monthes"] = range(1, 13)
        context["csts"] = CST.objects.all().order_by("name")
        
        # Color of forex column
        context["forex_color"] = JrcConfig.get_value_by_name("FOREX_COLUMN_COLOR", "lightblue")
        print "Forex: %s" % context["forex_color"]

        return context 
    
class ListSignalsView(ListView):
#    model = Signals
    template_name = "test/signals.html"
    
class VersionView(DetailView):
    template_name = "test/version.html"
    
    def get_object(self):
        return VersionView.get_revision()

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        context["revision"] = VersionView.get_revision()
        return context

    @staticmethod
    def get_revision():
        revisionId = 0
        file = os.path.join(TEMPLATE_DIRS, "revision.txt")
        txt = open(file, "r").read()
        if txt.startswith("$Rev:"):
#            print txt[5:].strip("$ ")
            revisionId = txt[5:].strip("$ ")
        return revisionId

def readurl(request):
#    rq = urllib2.Request("http://ya.ru")
#    response = urllib2.urlopen(rq)
#    page = response.read()
#    print page
    return HttpResponse("Done")

def editpermissions(request, pk):
    return render_to_response(
                "test/editpermissions.html"
                , {
#                    "permissions": request.user.get_all_permissions()
                }
                , context_instance = RequestContext(request))


@permission_required("auth.jrc_pet_change", login_url = "/accounts/denied/")
def permissions(request):
#    if not request.user.has_perm("jrc.foo.change"):
#        return HttpResponseRedirect("/accounts/denied/?next=/test/permissions/")
    
    users = User.objects.all().filter(is_active = True)
#    apps = ContentType.objects.all().exclude(app_label__istartswith = "auth").exclude(app_label__istartswith = "test").exclude(app_label__istartswith = "asset").exclude(app_label__istartswith = "sessions")
#    print apps
#    print users
    return render_to_response(
                "test/permissions.html"
                , {
#                    "permissions": request.user.get_all_permissions()
                    "permissions": Permission.objects.filter(codename__startswith = "jrc_")
#                    , "apps": JrcApp.objects.all().order_by("pk")
                    , "users": users
#                    , "form": UserChangeForm()
                }
                , context_instance = RequestContext(request))

@login_required
def getjrcpermissions(request, pk):
    user_to_look = User.objects.get(pk = pk)
#    user_permissions = JrcAppUserPermission.objects.all().filter(user_id = pk)
    return render_to_response("test/getjrcpermissions.html"
                              , {
                                 "user_to_look": user_to_look
#                                 , "user_permissions": user_permissions
#                                 , "all_permissions": JRC_PERMISSION_CHOICES
                              }
                              , context_instance = RequestContext(request))

def upload_signals(request, **kwargs):
#    data = request.GET.get("data")
#    return HttpResponse("Data: %s" % data)
    if request.method == "POST":
        Signals.objects.all().delete()
        total_signals = 0
        for key in request.POST:
            if key.startswith("l_"):
                ar = request.POST.get(key).split(',')
                s = Signals()
                s.cst = ar[0]
                s.asset = ar[1]
                s.price = ar[5]
                s.save()

                total_signals += 1
        return HttpResponse("Got %d signals" % total_signals)
    return render_to_response("test/uploadsignals.html", {"time1": None}, context_instance = RequestContext(request))
    
def import_from_text(request):
    ar_names = ["FDAX-120", "FDAX-38", "FESX", "S&P-65", "S&P-30", "NQ", "DJ", "FGBL"]
    
    csts = CST.objects.all()
    for cst in csts:
        print "%d, %s" % (cst.pk, cst.name)
    
    for name in ar_names:
        try:
            cst = CST.objects.get(name = name)
            print "CST by %s is %s" % (name, cst.pk) 
        except CST.DoesNotExist:
            print "No CST w/ name: %s" % name
        
        
    trade = FuturesTradesAmount()
#    trade.cst
        
#    ar = [2.060, 2.040, 1.990, 2.020, 2.030, 2.030, 2.040, 2.040, 2.040, 2.050, 2.020, 2.080, 2.020, 2.060, 2.060, 2.060, 2.050, 2.070, 2.070, 2.080, 2.100, 2.080, 2.090, 2.300, 2.340, 2.340, 2.580, 2.590, 2.600, 2.780, 2.830, 3.010, 3.060, 3.330, 3.320, 3.570, 3.570, 4.010, 4.220, 3.950, 4.010, 3.990, 4.110, 4.270, 4.280, 3.690, 3.250, 2.550, 3.950, 4.000, 4.020, 3.950, 4.010, 4.020, 4.270, 4.290, 4.350, 3.750, 3.450, 2.290, 2.110, 1.240, 0.910, 0.810, 0.750, 0.710, 0.350, 0.330, 0.350, 0.350, 0.350, 0.350, 0.319, 0.319, 0.310, 0.310, 0.330, 0.354, 0.481, 0.426, 0.454, 0.701, 0.593, 0.498, 0.659, 0.71, 0.66, 0.97, 1.03, 1.12, 1.01, 0.0, 0.0, 0.0, 0.0, 0.0]
#    
#    pos = 0
#    getcontext().prec = 4
#    for year in range(2004, 2012):
#        for month in range(1, 13):
#            item = DvRatio()
#            item.year = year
#            item.month = month
#            item.value = ar[pos]
#            print item
##            item.save()
#            pos += 1
            
    
    pass
        

    
def timezone(request):
    time1 = datetime.datetime.now()
    os.environ["TZ"] = "Europe/Moscow"

    return render_to_response("test/timezone.html", {"time1": time1}, context_instance = RequestContext(request))

def message(request):
    messages.error(request, "message, extra_tags, fail_silently")
    
    if request.GET.get("x", "") != "":
        messages.add_message(request, CRITICAL, "Test")
        return HttpResponseRedirect("/test/message/list/")

    return render_to_response("test/message.html")

def message_list(request):
    return render_to_response("test/messagelist.html")

def getassetmarkets(request, id):
    return render_to_response("asset/getmarkets.html", { "markets": Market.objects.filter(asset = id) } )

def getparameterbypage(request, page):
    paginate_by = 20
    system_id = "0"
    market_id = "0"
    if request.GET.has_key("system_id"):
        system_id = request.GET.get("system_id")
        
    if request.GET.has_key("market_id"):
        market_id = request.GET.get("market_id")

    # TODO: make in more tidy
    if system_id != "0":
        if market_id != "0":
            jrc_parameters = JrcParameter.objects.filter(system_id = system_id).filter(market_id = market_id).order_by("-pk")[:paginate_by]
        else:
            jrc_parameters = JrcParameter.objects.filter(system_id = system_id).order_by("-pk")[:paginate_by]
    else:
        if market_id != "0":
            jrc_parameters = JrcParameter.objects.all().filter(market_id = market_id).order_by("-pk")[:paginate_by]
        else:
            jrc_parameters = JrcParameter.objects.all().order_by("-pk")[:paginate_by]
    
    return render_to_response("test/getparameterbypage.html", {"jrc_parameters": jrc_parameters})

def heading(request):
    systems = JrcSystem.objects.all()
    assets = Asset.objects.all()
    timelevels = TimeLevel.objects.all()

    if request.GET.has_key("asset_id"):
        markets = Market.objects.get(asset_id = request.GET.get("asset_id"))
    else:
        markets = ()
        
    if request.GET.has_key("asset_id"):
        jrc_parameters = JrcParameter.objects.filter(asset_id = request.GET.get("asset_id")).order_by("-pk")
    elif request.GET.has_key("market_id"):
        jrc_parameters = JrcParameter.objects.filter(asset_id = request.GET.get("market_id")).order_by("-pk")
    else:
        jrc_parameters = JrcParameter.objects.all().order_by("-pk")
        
    print jrc_parameters
        
    return render_to_response(
                              "test/heading.html"
                              , {
                                 "assets": assets
                                 , "markets": markets
                                 , "systems": systems
                                 , "jrc_parameters": jrc_parameters
                                 , "timelevels": timelevels
                              })

def start(request):
#    print HttpRequest.path
    return render_to_response(
                "test/start.html"
                , {}
                , context_instance = RequestContext(request))

def portfolio(request):
    csts = CST.objects.all().order_by("-pk")[:20]
    return render_to_response("test/portfolio.html", {"csts": csts})

def trading(request):
    return render_to_response("test/trading.html")

def development(request):
    return render_to_response("test/development.html")

def program(request):
    return render_to_response("test/program.html")

def test(request):
    logger = logging.getLogger(__name__)
    logger.debug("Test... Test... Test... Test... Test... Test... Test... ")

    cache_name = "trackrecord_%d_market" % 21
    market = cache.get(cache_name)
    if market is None:
        print "Selecting CST by PK #%d and storing in cache as %s" % (21, cache_name)
#        market = self.cst_id.market_direction_1.market_id
        market = CST.objects.get(pk = 21)
        cache.set(cache_name, market)
    else:
        print "Using market from cache..."


    cache_name = "test/tracks"
    tracks = cache.get(cache_name)
    if tracks is None:
        tracks = TrackRecordForex.objects.all()
        logger.info("Storing tracks in cache as %s" % cache_name)
        cache.set(cache_name, tracks)
    else:
        logger.info("Use tracks from cache")


    return render_to_response(
        "test/test.html", {
            "tracks": tracks
        }
        , context_instance = RequestContext(request))

def parse_csv(request, id):
    f = get_object_or_404(UploadFile, pk = id)
    
#    print "Filename %s" % f.import_file.file
#    print "Path %s" % f.import_file.path
    fp = open(f.import_file.path, "rb")
    csvReader = csv.reader(fp, delimiter = ",")

    # Pass list of tradings to template
    tlist = list()
    
    trading = None
    first = True

    for row in csvReader:
        # Parse only good lines, not titles :)
        if len(row) > 5:
            if first:
                # Need to create TradinglistNorm object and fill with entry info
                trading = TradinglistNorm()
                trading.entry_type = row[1]
                trading.entry_date = row[2]
                trading.entry_price = row[4]
                
                # Flag that entry info is filled, next line is exit
                first = False
                
            else:
                trading.exit_type = row[1]
                trading.exit_date = row[2]
                trading.exit_price = row[4]
                
                # Adds to list
                tlist.append(trading)

                # Flag that entry is finished, next line will be new
                first = True 
                

    
    return render_to_response("test/parse_csv.html", {"tlist": tlist})
#    for row in csvReader:
#        print j

def parse_xml(request, id):
#    f = get_object_or_404(UploadFile, pk = id)
#    
#    
#    tlist = list()
#    i = 1
##    doc = etree.parse("c:/temp/2011/04/eurnzd120.xml")
#    doc = etree.parse(f.import_file)
#    for child in doc.getroot():
#        print child.tag
#
##        trading = TradinglistNorm.objects.create()
#        trading = TradinglistNorm()
#
#        trading.entry_type = child[0 + i].text
#        trading.entry_date = child[1 + i][0].text
#        trading.entry_price = child[3 + i][0].text
##        
#        trading.exit_date = child[1 + i][0].text
#        trading.exit_price = child[3 + i][0].text
#        
#        tlist.append(trading)
##        trading.save()
#
#        # First row, where ID is
#        if i == 1:
##            trading.entry_type = child[1][0].text
##            trading.entry_date = child[2][0].text
#            i = 0
#        else:
##            trading.entry_type = child[0][0].text
##            trading.entry_date = child[1][0].text
#            i = 1
#
#    
#    return render_to_response("test/parse_xml.html", {"f": f, "tlist": tlist})
    pass
    

def create_all(request):
    ar_times = (10, 15, 20, 30, 60, 90, 120, 180, 240, 480)
    for t in ar_times:
        tl = TimeLevel()
        tl.status_id = 1
        tl.name = t
        if t > 60:
            tl.name = "%d hours" % (t / 60)
        tl.minutes = t
        #tl.save()
    
    ar_assets = ("Indices", "Commodities", "Bonds", "Shares", "Forex")
    for asset in ar_assets:
        a = Asset()
        a.name = asset
        a.created_at = datetime.datetime.now()
        #a.save()
    
    # Get asset for currencies
    a = Asset.objects.get(name = "Forex")
    
    ar_cur = ("GBPUSD", "GBPJPY", "GBPAUD", "GBPCAD", "GBPCHF", "GBPNZD", "AUDUSD", "AUDJPY", "AUDGBP", "AUDCAD", "AUDCHF", "AUDNZD", "CADUSD", "CADJPY", "CADGBP", "CADAUD", "CADCHF", "CADNZD", "CHFUSD", "CHFJPY", "CHFGBP", "CHFAUD", "CHFCAD", "CHFNZD", "NZDUSD", "NZDJPY", "NZDGBP", "NZDAUD", "NZDCAD", "NZDCHF")
    for c in ar_cur:
        m = Market()
        m.asset = a
        m.name = c
        m.created_at = datetime.datetime.now()
        #m.save()
    
    a = Asset.objects.get(name = "Commodities")
    
    ar_commodities = ("Gold", "Silver", "Sugar")
    for c in ar_commodities:
        m = Market()
        m.asset = a
        m.name = c
        m.created_at = datetime.datetime.now()
        #m.save()
    
    
def test_sql(request):
    qs = TrackRecordForex.get_tracks_by_month(2012, 4)
    for t in qs:
        print t.pk
    return render_to_response("test/testsql.html")
